package cn.fl.ref.crbaseinfo.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.dto.SysUlDatCfgDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.crbaseinfo.service.ICrBaseInfoService;
import cn.fl.ref.crbaseinfo.transform.CrBaseInfoVOTransform;
import cn.fl.ref.crbaseinfo.vo.CrAstRltvInfoVO;
import cn.fl.ref.crbaseinfo.vo.CrBaseInfoVO;
import cn.fl.ref.crbaseinfo.vo.CrUdtJrnlInfoVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.transform.SysUlDatCfgVOTransform;
import cn.fl.system.vo.SysUlDatCfgVO;
import fl.customer.facade.customer.constant.CustomerConstant;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.ref.crbaseinfo.condition.CrBaseInfoQueryCondition;
import fl.ref.crbaseinfo.constant.CrBaseInfoConstant;
import fl.ref.crbaseinfo.dto.CrAstRltvInfoDTO;
import fl.ref.crbaseinfo.dto.CrBaseInfoDTO;


/**
 * @Description: 授信基础信息
 */
@Controller
@RequestMapping("/rfbase/crbaseinfo")
public class CrBaseInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CrBaseInfoController.class);

	@Autowired
	private ICrBaseInfoService crBaseInfoService;
	
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	
	/**
	 * 附件服务
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;
	

	@Autowired
	private IUploadApiService uploadApiService;
	
	@Autowired
	IFriBaseInfoService friBaseInfoService;

	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		
		logger.info("加载crbaseinfo列表页面.");
		String fncInsId  = request.getParameter("fncInsId");
		String fncInsNm="";
	/*	String fncInsNm  = friBaseInfoVO.getFundRasInsNm();
		String fncInsShort  = request.getParameter("fncInsShort");*/
		if (StringUtils.isNotEmpty(fncInsId)) {
			FriBaseInfoVO friBaseInfoVO = this.friBaseInfoService.selectById(Long.valueOf(fncInsId), CurrentThreadContext.getCurrentSysCd(),
					CurrentThreadContext.getCurrentOrgCd());
			fncInsNm  = friBaseInfoVO.getFundRasInsNm();
		}
		this.crBaseInfoService.batchUpdateCrStSTOP(CrBaseInfoConstant.CR_BSC_INFO_CR_ST_STOP);
		//货币类型
		List<KeyValueVO> ccytpList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CCY_TP);
		//授信状态
		List<KeyValueVO> crstList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CR_ST);
		//资产占用种类
		List<KeyValueVO> astidList = this.getKvList(CrBaseInfoConstant.CR_AST_RLTV_AST_ID);
		//是否循环
		List<KeyValueVO> rvlcrList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_RVL_CR);
		//授信主体
		List<KeyValueVO> crsbjList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CR_SBJ);
		ModelAndView view = new ModelAndView("/rfbase/crbaseinfo/crBaseInfoList");
		view.addObject("fncInsId", fncInsId);
		view.addObject("fncInsNm", fncInsNm);
		/*view.addObject("fncInsShort", fncInsShort);*/
		view.addObject("ccytpList", ccytpList);
		view.addObject("crstList", crstList);
		view.addObject("astidList", astidList);
		view.addObject("rvlcrList", rvlcrList);
		view.addObject("crsbjList", crsbjList);
		BaseLogUtils.info(logger, "toListPage", "查询数据完成. DATA:" + JSONObject.toJSONString(fncInsId), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 初始化授信名称列表
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String crSbjQ = request.getParameter("crSbjQ");
		String crIdQ = request.getParameter("crIdQ");
		String crNmQ = request.getParameter("crNmQ");
		String stDtQ = request.getParameter("stDtQ");
		String edDtQ = request.getParameter("edDtQ");
		String crLmtMaxQ = request.getParameter("crLmtMaxQ");
		String crLmtMinQ = request.getParameter("crLmtMinQ");
		String crBalMaxQ = request.getParameter("crBalMaxQ");
		String crBalMinQ = request.getParameter("crBalMinQ");
		String crStQ = request.getParameter("crStQ");
		String rvlCrQ = request.getParameter("rvlCrQ");
		String fncInsIdQ = request.getParameter("fncInsIdQ");
		String fncInsNmQ = request.getParameter("fncInsNmQ");
		String astIdQ = request.getParameter("astIdQ");//查询资产种类
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		CrBaseInfoQueryCondition qc=new CrBaseInfoQueryCondition();
		
		if (StringUtils.isNotEmpty(fncInsIdQ)) {
			qc.setFncInsIdQ(Long.valueOf(fncInsIdQ));
		}
		if (StringUtils.isNotEmpty(fncInsNmQ)) {
			qc.setFncInsNmQ(fncInsNmQ);
		}
		if (StringUtils.isNotEmpty(crSbjQ)) {
			qc.setCrSbjQ(crSbjQ);
		}
		if (StringUtils.isNotEmpty(crIdQ)) {
			qc.setCrIdQ(crIdQ);
		}
		if (StringUtils.isNotEmpty(crNmQ)) {
			qc.setCrNmQ(crNmQ);
		}
		if (StringUtils.isNotEmpty(stDtQ)) {
			Date s = DateUtils.formatStringToDate(stDtQ, DateUtils.YYYY_MM_DD);
			qc.setStDtQ(s);
		}
		if (StringUtils.isNotEmpty(edDtQ)) {
			Date s = DateUtils.formatStringToDate(edDtQ, DateUtils.YYYY_MM_DD);
			 qc.setEdDtQ(s);
		}
		if (StringUtils.isNotEmpty(crLmtMaxQ)) {
			BigDecimal crLmtMaxQChange=new BigDecimal(crLmtMaxQ);
			qc.setCrLmtMaxQ(crLmtMaxQChange);
		}
		if (StringUtils.isNotEmpty(crLmtMinQ)) {
			BigDecimal crLmtMinQChange=new BigDecimal(crLmtMinQ);
			qc.setCrLmtMinQ(crLmtMinQChange);
		}
		if (StringUtils.isNotEmpty(crBalMaxQ)) {
			BigDecimal crBalMaxQChange=new BigDecimal(crBalMaxQ);
			qc.setCrBalMaxQ(crBalMaxQChange);
		}
		if (StringUtils.isNotEmpty(crBalMinQ)) {
			BigDecimal crBalMinQChange=new BigDecimal(crBalMinQ);
			qc.setCrBalMinQ(crBalMinQChange);
		}
		if (StringUtils.isNotEmpty(crStQ)) {
			qc.setCrStQ(Integer.parseInt(crStQ));
		}
		if (StringUtils.isNotEmpty(rvlCrQ)) {
			qc.setRvlCrQ(Integer.parseInt(rvlCrQ));
		}
		if (StringUtils.isNotEmpty(astIdQ)) {
			qc.setAstIdQ(Integer.parseInt(astIdQ));
		}
		if (StringUtils.isNotEmpty(request.getParameter("isBa"))) {
			qc.setIsBa(request.getParameter("isBa"));
		}
		page.setCondition(qc);
		
		Pager pager = this.crBaseInfoService.searchListPage(page);
		List<CrBaseInfoDTO> listDTO = (List<CrBaseInfoDTO>)pager.getResultList();
		List<CrBaseInfoVO> list=CrBaseInfoVOTransform.toVOList(listDTO);
		this.setCrDicInfo(list,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
		ListPageVO<CrBaseInfoVO> listPage = new ListPageVO<CrBaseInfoVO>(list, pager.getTotalCount());

		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	
	/**
	 * 到授信新增修改页面的-授信主体下拉框选项
	 */
	@RequestMapping(value = "/getCrsbjList.do", method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody List<KeyValueVO> getCrsbjList(HttpServletRequest request, HttpServletResponse response) {
		//授信主体
		List<KeyValueVO> crsbjList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CR_SBJ);
		return crsbjList;
	}

	/**
	 * 到授信新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String fncInsId  = request.getParameter("fncInsId");
		String lgcId = request.getParameter("lgcId");
		//货币类型
		List<KeyValueVO> ccytpList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CCY_TP);
		//授信状态
		List<KeyValueVO> crstList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CR_ST);
		//资产占用种类
		List<KeyValueVO> astidList = this.getKvList(CrBaseInfoConstant.CR_AST_RLTV_AST_ID);
		//是否循环
		List<KeyValueVO> rvlcrList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_RVL_CR);
		//授信主体
		List<KeyValueVO> crsbjList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CR_SBJ);
		ModelAndView view = new ModelAndView("/rfbase/crbaseinfo/crBaseInfoAdd");
		view.addObject("fncInsId", fncInsId);
		view.addObject("ccytpList", ccytpList);
		view.addObject("crstList", crstList);
		view.addObject("astidList", astidList);
		view.addObject("rvlcrList", rvlcrList);
		view.addObject("crsbjList", crsbjList);
		view.addObject("lgcId", lgcId);
		BaseLogUtils.info(logger, "toAddPage", "查询数据完成. DATA:" + JSONObject.toJSONString(fncInsId)+"lgcId:"+JSONObject.toJSONString(lgcId), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 授信新增初始化
	 */
	@RequestMapping(value = "/toAddInit.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO toAddInit(HttpServletRequest request, HttpServletResponse response) {
		String fncInsId = request.getParameter("fncInsId");
		CrBaseInfoQueryCondition qc=new CrBaseInfoQueryCondition();
		qc.setFncInsIdQ(Long.valueOf(fncInsId));
		qc.setCurTmQ(new Date());
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增初始化成功!");
		List<CrBaseInfoVO> historyListValid=null;
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			FriBaseInfoVO friBaseInfoVO = this.friBaseInfoService.selectById(Long.valueOf(fncInsId), CurrentThreadContext.getCurrentSysCd(),
					CurrentThreadContext.getCurrentOrgCd());
			String fncInsNm  = friBaseInfoVO.getFundRasInsNm();
			String fncInsShort = friBaseInfoVO.getInsAbb();
			historyListValid = this.crBaseInfoService.selectHisCrListValid(qc);
			this.setCrDicInfo(historyListValid,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
			map.put("fncInsNm", fncInsNm);
			map.put("fncInsShort", fncInsShort);
			map.put("historyListValid", historyListValid);
			result.setData(map);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "toAddInit", "获取数据失败,融资机构编号["+fncInsId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "toAddInit", "获取数据失败,融资机构编号["+fncInsId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		String fncInsId = request.getParameter("fncInsId");
		String crNm = request.getParameter("crNm");
		String crCtrNo = request.getParameter("crCtrNo");
		String crSbj = request.getParameter("crSbj");
		String crLmt = request.getParameter("crLmt");
		String rvlCr = request.getParameter("rvlCr");
		String ccyTp = request.getParameter("ccyTp");
		String stDt = request.getParameter("stDt");
		String edDt = request.getParameter("edDt");
		String rmrk = request.getParameter("rmrk");
		String crId = request.getParameter("fncInsShort");
		String scmDsc = request.getParameter("scmDsc");
		String isPartIn = request.getParameter("isPartIn");//是否参与合同审核
		
		// 资产关联表的数据
		String astArray = request.getParameter("astArray"); 
		JSONArray astJsonArray = JSONArray.parseArray(astArray);
		List<CrAstRltvInfoVO> crAstRltvInfoList=new ArrayList<CrAstRltvInfoVO>();
		if (astJsonArray.size() > 0) {
			for (int i = 0; i < astJsonArray.size(); i++) {
				CrAstRltvInfoVO astRltvInfoVO = JSONObject.toJavaObject(astJsonArray.getJSONObject(i), CrAstRltvInfoVO.class);
				crAstRltvInfoList.add(astRltvInfoVO);
			}
		}
        
		//关联的历史授信表的数据
		String historyArray = request.getParameter("historyArray"); 
		JSONArray historyJSONArray = JSONArray.parseArray(historyArray);
		List<CrBaseInfoVO> crBaseInfoHisList=new ArrayList<CrBaseInfoVO>();
		if (historyJSONArray.size() > 0) {
			for (int i = 0; i < historyJSONArray.size(); i++) {
				CrBaseInfoVO historyInfoVO = JSONObject.toJavaObject(historyJSONArray.getJSONObject(i), CrBaseInfoVO.class);
				crBaseInfoHisList.add(historyInfoVO);
			}
		}
		
		CrBaseInfoVO  crBaseInfoEntity=new CrBaseInfoVO();
		if (StringUtils.isNotEmpty(crId)) {
			crBaseInfoEntity.setCrId(crId);
		}
		if (StringUtils.isNotEmpty(fncInsId)) {
			crBaseInfoEntity.setFncInsId(Long.valueOf(fncInsId));
		}
		if (StringUtils.isNotEmpty(crNm)) {
			crBaseInfoEntity.setCrNm(crNm);
		}
		if (StringUtils.isNotEmpty(crCtrNo)) {
			crBaseInfoEntity.setCrCtrNo(crCtrNo);
		}
		if (StringUtils.isNotEmpty(crSbj)) {
			crBaseInfoEntity.setCrSbj(crSbj);
		}
		if (StringUtils.isNotEmpty(crLmt)) {
			BigDecimal crLmtc=new BigDecimal(crLmt);
			crBaseInfoEntity.setCrLmt(crLmtc);
		}
		if (StringUtils.isNotEmpty(rvlCr)) {
			crBaseInfoEntity.setRvlCr(Integer.valueOf(rvlCr));
		}
		if (StringUtils.isNotEmpty(ccyTp)) {
			crBaseInfoEntity.setCcyTp(Integer.valueOf(ccyTp));
		}
		if (StringUtils.isNotEmpty(stDt)) {
			crBaseInfoEntity.setStDt(DateUtils.formatStringToDate(stDt, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(edDt)) {
			crBaseInfoEntity.setEdDt(DateUtils.formatStringToDate(edDt, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(rmrk)) {
			crBaseInfoEntity.setRmrk(rmrk);
		}
		if (StringUtils.isNotEmpty(scmDsc)) {
			crBaseInfoEntity.setScmDsc(scmDsc);
		}
		if (StringUtils.isNotEmpty(isPartIn)) {//是否参与合同审核
			crBaseInfoEntity.setIsPartIn(Long.parseLong(isPartIn));
		}
		String zgFlag=request.getParameter("zgFlag");//是否资管
		if (StringUtils.isNotEmpty(zgFlag)) {
			crBaseInfoEntity.setZgFlag(Integer.parseInt(zgFlag));
		}else {
			crBaseInfoEntity.setZgFlag(0);
		}
		crBaseInfoEntity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		crBaseInfoEntity.setCrtTm(new Date());
		crBaseInfoEntity.setIsValid(BaseConstant.IS_YESNO_YES); // 有效
		crBaseInfoEntity.setIsDel(BaseConstant.IS_YESNO_NO); // 未删除
		crBaseInfoEntity.setCrSt(CrBaseInfoConstant.CR_BSC_INFO_CR_ST_NOCR);
		crBaseInfoEntity.setIncCrId("");
		crBaseInfoEntity.setCrAstRltvInfoListVO(crAstRltvInfoList);
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		
		try {
			Long mainId = this.crBaseInfoService.add(crBaseInfoEntity,crBaseInfoHisList);
			result.setData(mainId);
			//上传附件
			uploadAttchment(request, result, mainId);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("新增成功!");
			BaseLogUtils.info(logger, "add", "新增数据 ,name["+crNm+"]. ID:"+mainId, CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败,name["+crNm+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
			BaseLogUtils.error(logger, "add", "新增数据失败,name["+crNm+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String crId = request.getParameter("crId");
		String lgcId = request.getParameter("lgcId");
		//货币类型
		List<KeyValueVO> ccytpList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CCY_TP);
		//授信状态
		List<KeyValueVO> crstList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CR_ST);
		//资产占用种类
		List<KeyValueVO> astidList = this.getKvList(CrBaseInfoConstant.CR_AST_RLTV_AST_ID);
		//是否循环
		List<KeyValueVO> rvlcrList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_RVL_CR);
		//授信主体
		List<KeyValueVO> crsbjList = this.getKvList(CrBaseInfoConstant.CR_BSC_INFO_CR_SBJ);
		ModelAndView view = new ModelAndView("/rfbase/crbaseinfo/crBaseInfoDetail");
		view.addObject("crId", crId);
		view.addObject("ccytpList", ccytpList);
		view.addObject("crstList", crstList);
		view.addObject("astidList", astidList);
		view.addObject("rvlcrList", rvlcrList);
		view.addObject("crsbjList", crsbjList);
		view.addObject("lgcId", lgcId);
		BaseLogUtils.info(logger, "toDetailPage", "查询数据完成. DATA:" + JSONObject.toJSONString(crId)+"lgcId:"+JSONObject.toJSONString(lgcId), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 得到一条记录
	 */
	@RequestMapping(value = "/getByLgcId.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object getByCrId(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String lgcId = request.getParameter("lgcId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功!");
		CrBaseInfoVO crBaseInfoVO = null;
		List<CrBaseInfoVO> historyList =null;
		CrBaseInfoQueryCondition qc=new CrBaseInfoQueryCondition();
		Long idQ=0L;
		if (StringUtils.isEmpty(lgcId)) {
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			crBaseInfoVO = this.crBaseInfoService.selectById(Long.valueOf(lgcId));
			//将CrBaseInfoVO转化为List，为Code添加Name
			List<CrBaseInfoVO> crBaseInfoVOList=new ArrayList<CrBaseInfoVO>();
			crBaseInfoVOList.add(crBaseInfoVO);
			this.setCrDicInfo(crBaseInfoVOList,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
			crBaseInfoVO=crBaseInfoVOList.get(0);
			
			Long id=crBaseInfoVO.getId();
			List<SysUlDatCfgVO> sysUlDatCfgVOs = searchSysUlDatCfgList(Long.valueOf(id));
			Long fncInsId = crBaseInfoVO.getFncInsId();
			String crId=crBaseInfoVO.getCrId();
			if (StringUtils.isEmpty(crId)) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
			}
			qc=new CrBaseInfoQueryCondition();
			qc.setFncInsIdQ(fncInsId);
			qc.setIncCrIdQ(crId);
			qc.setIdQ(idQ);
			historyList = this.crBaseInfoService.selectHisCrList(qc);
			//为Code添加Name
			this.setCrDicInfo(historyList,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
			map.put("crBaseInfoVO", crBaseInfoVO);
			map.put("historyList", historyList);
			result.setData(map);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getByCrId", "获取数据失败,授信逻辑编号["+lgcId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "getByCrId", "获取数据失败,授信逻辑编号["+lgcId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	
	/**
	 * 授信修改初始化
	 */
	@RequestMapping(value = "/toUpdateInit.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object toUpdateInit(HttpServletRequest request, HttpServletResponse response) {
		String lgcId = request.getParameter("lgcId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功!");
		CrBaseInfoVO crBaseInfoVOEntity =null;
		List<CrBaseInfoVO> historyListValid =null;
		CrBaseInfoQueryCondition qc=new CrBaseInfoQueryCondition();
		Map<String, Object> map=new HashMap<String, Object>();
		Long idQ=0L;
		if (StringUtils.isNotEmpty(lgcId)) {
			idQ=Long.valueOf(lgcId);
		}else{
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		qc.setIdQ(idQ);
		qc.setCurTmQ(new Date());
		try {
			crBaseInfoVOEntity = this.crBaseInfoService.selectById(Long.valueOf(lgcId));
			
			//将CrBaseInfoVO转化为List，为Code添加Name
			List<CrBaseInfoVO> crBaseInfoVOList=new ArrayList<CrBaseInfoVO>();
			crBaseInfoVOList.add(crBaseInfoVOEntity);
			this.setCrDicInfo(crBaseInfoVOList,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
			crBaseInfoVOEntity=crBaseInfoVOList.get(0);
			
			Long fncInsId=crBaseInfoVOEntity.getFncInsId();
			String crId=crBaseInfoVOEntity.getCrId();
			qc.setIncCrIdQ(crId);
			qc.setFncInsIdQ(fncInsId);
			historyListValid = this.crBaseInfoService.selectHisCrListValid(qc);
			//为Code添加Name
			this.setCrDicInfo(historyListValid,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
			
			map.put("crBaseInfoVO", crBaseInfoVOEntity);
			map.put("historyListValid", historyListValid);
			map.put("crStContant", CrBaseInfoConstant.CR_BSC_INFO_CR_ST_PASS);
			result.setData(map);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "toUpdateInit", "获取数据失败,授信逻辑编号["+lgcId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "toUpdateInit", "获取数据失败,授信逻辑编号["+lgcId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 修改
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		String fncInsId = request.getParameter("fncInsId");
		String crId = request.getParameter("crId");
		String crNm = request.getParameter("crNm");
		String crCtrNo = request.getParameter("crCtrNo");
		String crSbj = request.getParameter("crSbj");
		String crLmt = request.getParameter("crLmt");
		String rvlCr = request.getParameter("rvlCr");
		String ccyTp = request.getParameter("ccyTp");
		String stDt = request.getParameter("stDt");
		String edDt = request.getParameter("edDt");
		String rmrk = request.getParameter("rmrk");
		String lgcId = request.getParameter("lgcId");
		String crSt = request.getParameter("crSt");
		String scmDsc = request.getParameter("scmDsc");
		String isPartIn = request.getParameter("isPartIn");
		//授信信息
		CrBaseInfoVO  crBaseInfoEntity=new CrBaseInfoVO();
		if (StringUtils.isNotEmpty(lgcId)) {
			crBaseInfoEntity.setId(Long.valueOf(lgcId));
		}
		if (StringUtils.isNotEmpty(crSt)) {
			crBaseInfoEntity.setCrSt(Integer.valueOf(crSt));
		}
		if (StringUtils.isNotEmpty(crId)) {
			crBaseInfoEntity.setCrId(crId);
		}
		if (StringUtils.isNotEmpty(fncInsId)) {
			crBaseInfoEntity.setFncInsId(Long.valueOf(fncInsId));
		}
		if (StringUtils.isNotEmpty(crNm)) {
			crBaseInfoEntity.setCrNm(crNm);
		}
		if (StringUtils.isNotEmpty(crCtrNo)) {
			crBaseInfoEntity.setCrCtrNo(crCtrNo);
		}
		if (StringUtils.isNotEmpty(crSbj)) {
			crBaseInfoEntity.setCrSbj(crSbj);
		}
		if (StringUtils.isNotEmpty(crLmt)) {
			BigDecimal crLmtc=new BigDecimal(crLmt);
			crBaseInfoEntity.setCrLmt(crLmtc);
		}
		if (StringUtils.isNotEmpty(rvlCr)) {
			crBaseInfoEntity.setRvlCr(Integer.valueOf(rvlCr));
		}
		if (StringUtils.isNotEmpty(ccyTp)) {
			crBaseInfoEntity.setCcyTp(Integer.valueOf(ccyTp));
		}
		if (StringUtils.isNotEmpty(stDt)) {
			crBaseInfoEntity.setStDt(DateUtils.formatStringToDate(stDt, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(edDt)) {
			crBaseInfoEntity.setEdDt(DateUtils.formatStringToDate(edDt, DateUtils.YYYY_MM_DD));
		}
		if (StringUtils.isNotEmpty(rmrk)) {
			crBaseInfoEntity.setRmrk(rmrk);
		}
		if (StringUtils.isNotEmpty(scmDsc)) {
			crBaseInfoEntity.setScmDsc(scmDsc);
		}
		if (StringUtils.isNotEmpty(isPartIn)) {//是否参与合同审核
			crBaseInfoEntity.setIsPartIn(Long.parseLong(isPartIn));
		}
		String zgFlag=request.getParameter("zgFlag");//是否资管
		if (StringUtils.isNotEmpty(zgFlag)) {
			crBaseInfoEntity.setZgFlag(Integer.parseInt(zgFlag));
		}else {
			crBaseInfoEntity.setZgFlag(0);
		}
		crBaseInfoEntity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		crBaseInfoEntity.setMdfTm(new Date());
		
		// 资产关联表的数据
		String astArray = request.getParameter("astArray"); 
		JSONArray astJsonArray = JSONArray.parseArray(astArray);
		List<CrAstRltvInfoVO> crAstRltvInfoList=new ArrayList<CrAstRltvInfoVO>();
		if (astJsonArray.size() > 0) {
			for (int i = 0; i < astJsonArray.size(); i++) {
				CrAstRltvInfoVO astRltvInfoVO = JSONObject.toJavaObject(astJsonArray.getJSONObject(i), CrAstRltvInfoVO.class);
				crAstRltvInfoList.add(astRltvInfoVO);
			}
		}
        
		//关联的历史授信表的数据
		String historyArray = request.getParameter("historyArray"); 
		JSONArray historyJSONArray = JSONArray.parseArray(historyArray);
		List<CrBaseInfoVO> crBaseInfoHisList=new ArrayList<CrBaseInfoVO>();
		if (historyJSONArray.size() > 0) {
			for (int i = 0; i < historyJSONArray.size(); i++) {
				CrBaseInfoVO historyInfoVO = JSONObject.toJavaObject(historyJSONArray.getJSONObject(i), CrBaseInfoVO.class);
				crBaseInfoHisList.add(historyInfoVO);
			}
		}
			
		
		
		crBaseInfoEntity.setCrAstRltvInfoListVO(crAstRltvInfoList);
		CrUdtJrnlInfoVO crUdtJrnlInfoEntity=new CrUdtJrnlInfoVO();
		//如果授信属于正常，保存修改记录
		if (StringUtils.isNotEmpty(crSt)) {
			crBaseInfoEntity.setCrSt(Integer.valueOf(crSt));
			if(Integer.valueOf(crSt)==CrBaseInfoConstant.CR_BSC_INFO_CR_ST_PASS||Integer.valueOf(crSt)==CrBaseInfoConstant.CR_BSC_INFO_CR_ST_STOP){
				String udtCnt = request.getParameter("udtCnt");
				if (StringUtils.isNotEmpty(udtCnt)) {
					crBaseInfoEntity.setCrSt(CrBaseInfoConstant.CR_BSC_INFO_CR_ST_NOCR);
					crUdtJrnlInfoEntity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
					crUdtJrnlInfoEntity.setCrId(crId);
					crUdtJrnlInfoEntity.setUdtCnt(udtCnt);
					crUdtJrnlInfoEntity.setCrtTm(new Date());
				}
			}
		}
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		try {
			
			this.crBaseInfoService.modify(crBaseInfoEntity, crBaseInfoHisList,crUdtJrnlInfoEntity);
			Long id=crBaseInfoEntity.getId();
			result.setData(id);
			//上传附件
			uploadAttchment(request, result, id);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("更新成功!");
			BaseLogUtils.info(logger, "modify", "修改数据,id["+crNm+"].", CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改数据失败,id["+crNm+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误");
			BaseLogUtils.error(logger, "modify", "修改数据失败,id["+crNm+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/remove.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO remove(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String crId = request.getParameter("crId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		try {
			this.crBaseInfoService.removeByCrId(crId);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("删除成功!");
			BaseLogUtils.info(logger, "remove", "删除数据,主键["+crId+"].", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "remove", "删除数据失败,主键["+crId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "remove", "删除数据失败,主键["+crId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 删除资产信息数据
	 */
	@RequestMapping(value = "/removeCrAstRltvById.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeCrAstRltvById(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		try {
			this.crBaseInfoService.removeCrAstRltvById(Long.valueOf(id));
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("删除成功!");
			BaseLogUtils.info(logger, "removeCrAstRltvById", "删除数据,主键["+id+"].", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeCrAstRltvById", "删除数据失败,主键["+id+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "removeCrAstRltvById", "删除数据失败,主键["+id+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 数据字典方法
	 * 
	 * @param grpCd
	 * @return
	 */
	private List<KeyValueVO> getKvList(String grpCd) {
		List<KeyValueVO> kvList = new ArrayList<>();
		try {
			List<SysDictionaryDTO> sysDictionaryDTOList = this.sysDictionaryApiService.searchGroup(CurrentThreadContext.getCurrentSysCd(),
					CurrentThreadContext.getCurrentOrgCd(), grpCd);
			if (CollectionUtils.isNotEmpty(sysDictionaryDTOList)) {
				for (SysDictionaryDTO sysDictionaryDTO : sysDictionaryDTOList) {
					KeyValueVO keyValueVO = new KeyValueVO();
					keyValueVO.setKey(sysDictionaryDTO.getCode());
					keyValueVO.setValue(sysDictionaryDTO.getCodeNm());
					kvList.add(keyValueVO);
				}
			}
		} catch (BaseException e) {
			BaseLogUtils.info(logger, "getKvList", "获取字典项组" + grpCd + "失败.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception e) {
			BaseLogUtils.error(logger, "getKvList", "获取字典项组" + grpCd + "失败,系统错误.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return kvList;
	}
	
	private void uploadAttchment(HttpServletRequest request, DataResultVO result, Long id) {
		String attchmnt = request.getParameter("docArray");
		if(StringUtils.isNotEmpty(attchmnt)){
			//上传解析
			try{
				String cfgCd = PropertiesCacheUtils.getProperty(CustomerConstant.CST_BSCINFO_CFGCD);
				String cfgDtlCd = PropertiesCacheUtils.getProperty(CustomerConstant.CST_BSCINFO_CFGDTLCD);
				String tabNm = PropertiesCacheUtils.getProperty(CustomerConstant.CST_BSCINFO_TABNM);
				String cfgOrgCd = PropertiesCacheUtils.getProperty(CustomerConstant.CST_BSCINFO_CFGORG);
				Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, "客户主要信息附件!", null, null, false, cfgOrgCd);
				if(null == attchmntPass || attchmntPass == false){
					result.setInfo(result.getInfo()+"-附件上传失败!");
				}
			}catch(Exception e){
				result.setInfo(result.getInfo()+"-附件上传失败!");
			}
		}
	}
	
	/**
	 * 附件查询
	 * 
	 * @param condition
	 * @return
	 * @throws BaseException
	 */
	private List<SysUlDatCfgVO> searchSysUlDatCfgList(Long id) throws BaseException {
		// 查询资料配置，系统代码,组织架构代码,配置编号 ,业务主键
		SysUlDatCfgQueryCondition ulDatCfgQueryCondition = new SysUlDatCfgQueryCondition();
		ulDatCfgQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());// 系统代码

		ulDatCfgQueryCondition.setOrgCd(PropertiesCacheUtils.getProperty(CustomerConstant.CST_BSCINFO_CFGORG));// 组织架构代码
		// ulDatCfgQueryCondition.setOrgCd("10");// 组织架构代码
		ulDatCfgQueryCondition.setDataId(String.valueOf(id));// 业务主键
		List<String> cfgCdList = new ArrayList<>();
		ulDatCfgQueryCondition.setCfgCdList(cfgCdList);// 配置编号
		// cfgCdList.add("CST001");// 项目上传资料 配置编号
		cfgCdList.add(PropertiesCacheUtils.getProperty(CustomerConstant.CST_BSCINFO_CFGCD));// 项目上传资料 配置编号
		List<SysUlDatCfgDTO> sysUlDatCfgDTOList = this.uploadApiService.searchSysUlDatCfgList(ulDatCfgQueryCondition);

		return SysUlDatCfgVOTransform.toVOList(sysUlDatCfgDTOList);
	}
	
	/**
	 * 设置关于字典项信息
	 * @param listVO
	 */
	private void setCrDicInfo(List<CrBaseInfoVO> listVO, String sysCd, String orgCd) {
		if(CollectionUtils.isEmpty(listVO))return;
		try {
			Map<String, String> ccytpMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CrBaseInfoConstant.CR_BSC_INFO_CCY_TP);
			Map<String, String> crstMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CrBaseInfoConstant.CR_BSC_INFO_CR_ST);
			Map<String, String> rvlcrMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CrBaseInfoConstant.CR_BSC_INFO_RVL_CR);
			Map<String, String> crsbjMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CrBaseInfoConstant.CR_BSC_INFO_CR_SBJ);
			Map<String, String> astidMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CrBaseInfoConstant.CR_AST_RLTV_AST_ID);
			Map<String, String> isPartInMap = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CrBaseInfoConstant.CR_BSC_INFO_IS_PART_IN);
			
			for (CrBaseInfoVO crBaseInfoVO:listVO) {
				if(crBaseInfoVO.getCcyTp()!=null){
					if(ccytpMap.containsKey(crBaseInfoVO.getCcyTp().toString())){
						crBaseInfoVO.setCcyTpNm(ccytpMap.get(crBaseInfoVO.getCcyTp().toString()));
					}
				}
				if(crBaseInfoVO.getCrSt()!=null){
					if(crstMap.containsKey(crBaseInfoVO.getCrSt().toString())){
						crBaseInfoVO.setCrStNm(crstMap.get(crBaseInfoVO.getCrSt().toString()));
					}
				}
				if(crBaseInfoVO.getRvlCr()!=null){
					if(rvlcrMap.containsKey(crBaseInfoVO.getRvlCr().toString())){
						crBaseInfoVO.setRvlCrNm(rvlcrMap.get(crBaseInfoVO.getRvlCr().toString()));
					}
				}
				if(crBaseInfoVO.getIsPartIn()!=null){
					if(isPartInMap.containsKey(crBaseInfoVO.getIsPartIn().toString())){
						crBaseInfoVO.setIsPartInNm(isPartInMap.get(crBaseInfoVO.getIsPartIn().toString()));
					}
				}
				if(crBaseInfoVO.getCrSbj()!=null){
					String crSbjNm="";
					for (String key : crsbjMap.keySet()) {
						if(crBaseInfoVO.getCrSbj().contains(key)){
							crSbjNm +=crsbjMap.get(key)+"; ";
						}
					 }
					crBaseInfoVO.setCrSbjNm(crSbjNm);
				}
				List<CrAstRltvInfoVO> AstInfoList=crBaseInfoVO.getCrAstRltvInfoListVO();
				if(CollectionUtils.isEmpty(AstInfoList)){
					continue;
				}else{
					List<CrAstRltvInfoVO> AstInfoListnew=new ArrayList<CrAstRltvInfoVO>();
					for (CrAstRltvInfoVO crAstRltvInfoDTO : AstInfoList) {
						if(astidMap.containsKey(crAstRltvInfoDTO.getAstId())){
							crAstRltvInfoDTO.setAstNm(astidMap.get(crAstRltvInfoDTO.getAstId()));
							AstInfoListnew.add(crAstRltvInfoDTO);
						}
					}
					crBaseInfoVO.setCrAstRltvInfoListVO(AstInfoListnew);
				
				}
			}
			
		} catch (Exception e) {
			BaseLogUtils.error(logger, "setDicInfo", "获取DIC数据失败!");
		}
	}
	
	@RequestMapping(value = "/addFlowStart.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object addFlowStart(HttpServletRequest request, HttpServletResponse response) {

		String id = request.getParameter("id");
		String procDefKey = request.getParameter("procDefKey");
		String procDefId = request.getParameter("procDefId");
		String procNo = request.getParameter("procNo");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "addFlowStart", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		//add 发起流程参数 by gengchunlan 20180425
		Map<String, Object> startParams=new HashMap<String, Object>();
		CrBaseInfoVO crBaseInfo = crBaseInfoService.selectById(Long.valueOf(id));//根据ID获取授信主体信息
		String isPartIn="2";//是否参与合同审核  2不参与 1参与
		if(crBaseInfo!=null && crBaseInfo.getIsPartIn()!=null ){
			isPartIn=String.valueOf(crBaseInfo.getIsPartIn());
		}
		startParams.put("isPartIn",isPartIn);
		//end by gengchunlan 20180425
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			//流程定义Key和流程定义ID 如果是前端选择的则直接指定,如果不是则系统自动按照配置选择唯一一条记录,如果找不到会提示
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(CrBaseInfoConstant.REF_FLOW_S_H_CBI);
			flowStartParamsDTO.setProcDefKey(procDefKey);
			flowStartParamsDTO.setProcDefId(procDefId);
			flowStartParamsDTO.setProcNo(procNo);
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setBusinessKey(id);
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
			flowStartParamsDTO.setBusinessType(CrBaseInfoConstant.FLOW_BUSINESS_TYP_CR_BSC_INFO);//确认用不用
			flowStartParamsDTO.setModelTyp(CrBaseInfoConstant.FLOW_MODEL_TYP_CBI);//需要和流程配置中的模块类型匹配
			flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm()+"、授信流程大字段参数未定!");
			flowStartParamsDTO.setStartParams(startParams);
			
			DataResultDTO dataResultDTO = this.crBaseInfoService.addFlowStart(flowStartParamsDTO);
			if(!dataResultDTO.getCode().equals(BaseExceptionConstant.BASE_EXCEPTION_CODE_200)){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
			}
			if(null!=dataResultDTO && null!=dataResultDTO.getData()){
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO.getData();
				if(StringUtils.isNotBlank(flowStartedDTO.getNextOperUsrNames())){
	                result.setInfo("下一个节点操作人:"+flowStartedDTO.getNextOperUsrNames());
	            }else{
	                result.setInfo("流程发起成功");
	            }
			}
			/*if(null != dataResultDTO.getInfo() && StringUtils.isNotEmpty(dataResultDTO.getInfo())){
				StringBuffer info = new StringBuffer();
				info.append(result.getInfo());
				info.append(SysLogConstant.LOG_FLOW_NEXT_TASK_OPERATOR);
				info.append(dataResultDTO.getInfo());//操作人
				result.setInfo(info.toString());
			}*/
		} catch (BaseException e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(e.getMessage());
			BaseLogUtils.info(logger, "addFlowStart", "错误[BaseException],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" +e.getMessage(), CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		} catch (Exception e) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addFlowStart", "错误[Exception],请求参数：" + JSONObject.toJSONString(flowStartParamsDTO) + " -ERROR:" +e.getMessage(), CurrentThreadContext.getCurrentUserName());
			e.getStackTrace();
		}
		return result;
	}
	
	/**
	 * 获取历史授信的产品
	 */
	@RequestMapping(value = "/getAstInfoByCrId.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO getAstInfoByCrId(HttpServletRequest request, HttpServletResponse response) {
		String rvlCr = request.getParameter("rvlCr");
	    String crId = request.getParameter("crId");
	    if(StringUtils.isEmpty(rvlCr)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "授信循环类型不能为空");
		}
		if(StringUtils.isEmpty(crId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "授信编号不能为空");
		}
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增初始化成功!");
		List<CrAstRltvInfoVO> crAstRltvList=new ArrayList<CrAstRltvInfoVO>();
		try {
			crAstRltvList=this.crBaseInfoService.selectAstInfoByCrId(Integer.valueOf(rvlCr),crId);
			result.setData(crAstRltvList);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getAstInfoByCrId", "获取数据失败,融资机构编号["+crId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "getAstInfoByCrId", "获取数据失败,融资机构编号["+crId+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 授信合同编号查重
	 */
	@RequestMapping(value = "/getCnkiCrCtrNo.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO getCnkiCrCtrNo(HttpServletRequest request, HttpServletResponse response) {
	    String crCtrNo = request.getParameter("crCtrNo");
	    if(StringUtils.isEmpty(crCtrNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "授信合同编号不能为空");
		}
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增初始化成功!");
		boolean crCtrNoSum=false;
		try {
			crCtrNoSum=this.crBaseInfoService.selectCnkiCrCtrNo(crCtrNo);
			result.setData(crCtrNoSum);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getCnkiCrCtrNo", "获取数据失败,授信合同编号["+crCtrNo+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "getCnkiCrCtrNo", "获取数据失败,授信合同编号["+crCtrNo+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 授信合同编号查重
	 */
	@RequestMapping(value = "/getCnkiCrNm.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO getCnkiCrNm(HttpServletRequest request, HttpServletResponse response) {
	    String crNm = request.getParameter("crNm");
	    if(StringUtils.isEmpty(crNm)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "授信名称不能为空");
		}
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增初始化成功!");
		boolean crCtrNoSum=false;
		try {
			crCtrNoSum=this.crBaseInfoService.selectCnkiCrNm(crNm);
			result.setData(crCtrNoSum);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getCnkiCrNm", "获取数据失败,授信名称["+crNm+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "getCnkiCrNm", "获取数据失败,授信名称["+crNm+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 废弃资产信息数据
	 */
	@RequestMapping(value = "/cancelCrRecord.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO cancelCrRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isEmpty(id)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "授信逻辑编号不能为空");
		}
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "废弃成功!");
		CrBaseInfoVO crBaseInfoVO=new CrBaseInfoVO();
		crBaseInfoVO.setId(Long.valueOf(id));
		crBaseInfoVO.setCrSt(CrBaseInfoConstant.CR_BSC_INFO_CR_ST_NOPASS);
		try {
			this.crBaseInfoService.modify(crBaseInfoVO);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			result.setInfo("废弃成功!");
			BaseLogUtils.info(logger, "cancelCrRecord", "废弃数据,主键["+id+"].", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "cancelCrRecord", "废弃数据失败,主键["+id+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "cancelCrRecord", "废弃数据失败,主键["+id+"]."+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 到启用授信页面
	 */
	@RequestMapping(value = "/toEnableCrPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toEnableCrPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String flag = request.getParameter("flag");
		ModelAndView view = new ModelAndView("/rfbase/crbaseinfo/crBaseInfoEnable");
		if(StringUtils.isNotEmpty(id)){
			CrBaseInfoVO crBaseInfoVo = this.crBaseInfoService.selectById(Long.valueOf(id));
			view.addObject("crBaseInfoVo", crBaseInfoVo);
		}
		view.addObject("id", id);
		view.addObject("flag", flag);
		BaseLogUtils.info(logger, "toEnableCrPage", "查询数据完成. DATA:" + JSONObject.toJSONString(id)+"flag:"+JSONObject.toJSONString(flag), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 启用/停用授信信息数据
	 */
	@RequestMapping(value = "/switchCrRecord.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public DataResultVO switchCrRecord(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String flag = request.getParameter("flag");
		String edDt = request.getParameter("edDt");
		if(StringUtils.isEmpty(id)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "授信逻辑编号不能为空");
		}
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		CrBaseInfoVO crBaseInfoVO=new CrBaseInfoVO();
		crBaseInfoVO.setId(Long.valueOf(id));
		crBaseInfoVO.setMdfTm(new Date());
		crBaseInfoVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		try {
			//授信备案
			if(StringUtils.isNotEmpty(flag) && "4".equals(flag)){
				result.setInfo("成功!");
				crBaseInfoVO.setIsBa("1");
			//判断是启用还是停用
			}else if(StringUtils.isNotEmpty(flag) && "1".equals(flag)){
				result.setInfo("启用成功!");
				crBaseInfoVO.setCrSt(CrBaseInfoConstant.CR_BSC_INFO_CR_ST_PASS);
				if(StringUtils.isNotEmpty(edDt)){
					crBaseInfoVO.setEdDt(DateUtils.formatStringToDate(edDt, DateUtils.YYYY_MM_DD));
				}else{//授信结束日期可为空
					crBaseInfoVO.setEdDt(null);
				}
			}else{
				result.setInfo("停用成功!");
				crBaseInfoVO.setCrSt(CrBaseInfoConstant.CR_BSC_INFO_CR_ST_STOP);
				CrBaseInfoVO vo = this.crBaseInfoService.selectById(Long.valueOf(id));
				crBaseInfoVO.setEdDt(vo.getEdDt());//结束日期不变
				
			}
			boolean success = this.crBaseInfoService.modify(crBaseInfoVO);
			if(!success){
				result.setInfo("操作失败!");
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				BaseLogUtils.info(logger, "switchCrRecord", "启用/停用授信数据失败1,主键["+id+"].", CurrentThreadContext.getCurrentUserName());
			}else{
				BaseLogUtils.info(logger, "switchCrRecord", "启用/停用授信数据成功,主键["+id+"].", CurrentThreadContext.getCurrentUserName());
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "switchCrRecord", "启用/停用授信数据失败2,主键["+id+"].", CurrentThreadContext.getCurrentUserName(), ex);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "switchCrRecord", "启用/停用授信数据失败3,主键["+id+"].", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
}

